<template>
  <Modal :modelValue="modelValue" :title="title" @close="handleCloseDialog" @open="handleOpenDialog" width="635px"
    :fullscreen="false">
    <el-form ref="menuFormRef" :model="form" :rules="rules" label-width="auto" :inline="true" class="menu-form">
      <el-form-item label="菜单类型" prop="type">
        <el-radio-group v-model="form.type" @change="handleMenuTypeChange">
          <el-radio-button :value="0" label="目录" />
          <el-radio-button :value="1" label="菜单" />
          <el-radio-button :value="2" label="按钮" />
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="form.type !== MenuTypeEnum.BUTTON" label="菜单图标" prop="icon">
        <!-- 图标选择器 -->
        <icon-select v-model="form.icon" class="icon-select" />
      </el-form-item>
      <el-form-item label="菜单标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入菜单标题" style="width:495px" />
      </el-form-item>

      <el-form-item label="外链菜单" prop="i_frame" v-if="form.type !== MenuTypeEnum.BUTTON" style="width:170px">
        <el-radio-group v-model="form.i_frame">
          <el-radio-button :value="1" label="是" />
          <el-radio-button :value="0" label="否" />
        </el-radio-group>
      </el-form-item>

      <!-- 权限标识 -->
      <el-form-item v-if="form.type == MenuTypeEnum.BUTTON || form.type == MenuTypeEnum.MENU" label="权限标识"
        prop="permission">
        <el-input v-model="form.permission" placeholder="user:add" />
      </el-form-item>

      <el-form-item v-if="form.type === MenuTypeEnum.MENU" label="菜单缓存" style="width:170px">
        <el-radio-group v-model="form.cache">
          <el-radio-button :value="1" label="是" />
          <el-radio-button :value="0" label="否" />
        </el-radio-group>
      </el-form-item>

      <el-form-item v-if="form.type !== MenuTypeEnum.BUTTON" prop="hidden" label="菜单可见" style="width:170px">
        <el-radio-group v-model="form.hidden">
          <el-radio-button :value="0" label="是" />
          <el-radio-button :value="1" label="否" />
        </el-radio-group>
      </el-form-item>

      <el-form-item v-if="form.type == MenuTypeEnum.CATALOG || form.type == MenuTypeEnum.MENU" prop="path" label="路由地址">
        <el-input v-if="form.type == MenuTypeEnum.CATALOG" v-model="form.path" placeholder="system" />
        <el-input v-else v-model="form.path" placeholder="user" />
      </el-form-item>


      <el-form-item v-if="form.type == MenuTypeEnum.MENU" prop="name" label="组件名称">
        <el-input v-model="form.name" placeholder="User" />
      </el-form-item>


      <el-form-item v-if="form.type == MenuTypeEnum.MENU" label="组件">
        <el-input v-model="form.component" placeholder="组件" style="width:495px">
          <template v-if="form.type == MenuTypeEnum.MENU" #prepend>src/views/</template>
          <template v-if="form.type == MenuTypeEnum.MENU" #append>.vue</template>
        </el-input>
      </el-form-item>

      <el-form-item label="排序" prop="menu_sort">
        <el-input-number v-model="form.menu_sort" controls-position="right" :min="0" />
      </el-form-item>

      <el-form-item label="父级菜单" prop="pid">
        <el-tree-select v-model="form.pid" placeholder="选择上级菜单" :data="parentMenuData" filterable check-strictly
          :props="{ children: 'children', hasChildren: 'children', label: 'title', value: 'menu_id' }"
          :render-after-expand="false" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="modal-footer">
        <el-button type="primary" @click="handleSubmitForm">确 定</el-button>
        <el-button @click="handleCloseDialog">取 消</el-button>
      </div>
    </template>
  </Modal>
</template>

<script setup lang="ts">
defineOptions({
  name: "MenuModal",
  inheritAttrs: false,
})

import MenuAPI, { MenuForm, MenuVO } from "@/api/menu"
import { MenuTypeEnum } from "@/enums/MenuTypeEnum"
import { buildTree } from "@/utils";

// 定义接收的属性
interface Props {
  modelValue: boolean
  menuItem?: MenuVO
  title?: string
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  title: '表单',
})

// 自定义事件
const emit = defineEmits<{
  submit: [form: MenuForm]
  close: []
}>()



const menuFormRef = ref(ElForm)
const loading = ref(false)


// 顶级菜单下拉选项
const parentMenuData = ref<OptionType[]>([])

// 初始菜单表单数据
const initialMenuform = ref<MenuForm>({
  menu_id: undefined,
  pid: 0,
  cache: 0,
  hidden: 0,
  menu_sort: 1,
  type: MenuTypeEnum.MENU, // 默认菜单
  alwaysShow: 0,
  keepAlive: 1,
  params: [],
})

// 菜单表单数据
const form = ref({ ...initialMenuform.value })

// 表单验证规则
const rules = reactive({
  pid: [{ required: true, message: "请选择顶级菜单", trigger: "blur" }],
  type: [{ required: true, message: "请选择菜单类型", trigger: "blur" }],
  title: [{ required: true, message: "请输入菜单标题", trigger: "blur" }],
  name: [{ required: true, message: "请输入路由名称", trigger: "blur" }],
  path: [{ required: true, message: "请输入路由路径", trigger: "blur" }],
  component: [{ required: true, message: "请输入组件路径", trigger: "blur" }],
  hidden: [{ required: true, message: "请选择是否隐藏", trigger: "blur" }],
})

const getMenuTree = () => {
  const queryCondition: QueryCondition = {
    and: [{ field: 'type', op: '!=', value: 2 }]
  }
  MenuAPI.query(queryCondition).then(res => {
    if (res.status === 200) {
      const rootData = {
        menu_id: 0,
        title: "顶级菜单"
      }
      res.data.push(rootData)
      parentMenuData.value = []
      parentMenuData.value = buildTree(res.data, 'menu_id', 'pid')
    }
  })
}
// 菜单类型切换
const handleMenuTypeChange = () => {
  // 如果菜单类型改变
  if (form.value.type !== initialMenuform.value.type) {
    if (form.value.type === MenuTypeEnum.MENU) {
      // 目录切换到菜单时，清空组件路径
      if (initialMenuform.value.type === MenuTypeEnum.CATALOG) {
        form.value.component = ""
      } else {
        // 其他情况，保留原有的组件路径
        form.value.path = initialMenuform.value.path
        form.value.component = initialMenuform.value.component
      }
    }
  }
}

/** 菜单保存提交 */
const handleSubmitForm = () => {
  menuFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      const menuId = form.value.menu_id
      if (menuId) {
        updateData()
      } else {
        saveData()
      }
    }
  })
}

const saveData = () => {
  loading.value = true
  MenuAPI.add(form.value).then((res) => {
    if (res.status === 200) {
      ElMessage.success("新增成功")
      emit('submit', res.data)
    }
  }).finally(() => { loading.value = false })
}

const updateData = () => {
  loading.value = true
  MenuAPI.update(form.value).then((res) => {
    if (res.status === 200) {
      ElMessage.success("新增成功")
      emit('submit', res.data)
    }
  }).finally(() => { loading.value = false })
}


// 打开弹窗
const handleOpenDialog = () => {

}

// 关闭弹窗
const handleCloseDialog = () => {
  if (menuFormRef.value) {
    menuFormRef.value.resetFields()
    menuFormRef.value.clearValidate()
  }
  form.value = Object.assign({}, initialMenuform.value)
  emit('close')
}


const getFormData = (menuId: number) => {
  MenuAPI.getFormData(menuId).then(res => {
    if (res.status === 200) {
      form.value = Object.assign({}, res.data)
    }
  })
}

//表单传递数据
watch(() => props.menuItem, (newVal: any, oldVal) => {

  if (newVal.menu_id) {
    getFormData(newVal.menu_id)
  } else {
    form.value = Object.assign({}, newVal)
  }
  getMenuTree()

}, { immediate: true, deep: true })

</script>
<style lang="scss">
.menu-form {
  width: 100%;

  .el-input {
    width: 193px
  }

  .el-input-number {
    width: 495px !important;

    .el-input {
      width: 495px !important;
    }
  }


  .el-select {
    width: 495px !important;
  }

  .icon-select {
    .el-input {
      width: 495px !important;
    }
  }
}
</style>
